//
//  JMPBase.m
//  nonghubao
//
//  Created by 王 文彬 on 13-2-25.
//  Copyright (c) 2013年 Chongqing Nonghubao Co., Ltd. All rights reserved.
//

#import "JMFBase.h"

@implementation JMFBase

@synthesize message = _message;
@synthesize error   = _error;
@synthesize status  = _status;
@synthesize data    = _data;

- (id)initWithJSONDictionary:(NSDictionary *)dictionary
{
    self = [super init];
    if (self) {
        if (dictionary) {
            [self parserJSONDictionary:dictionary];
        }
    }
    
    return self;
}


//
- (id)idValue:(NSString *)path
{
    return [self idForPath:path];
}


//
- (BOOL)boolValue:(NSString *)path
{
    return [[self idForPath:path] boolValue];
}


//
- (NSString *)stringValue:(NSString *)path
{
    return [self idForPath:path];
}


//
- (NSNumber *)numberValue:(NSString *)path
{
    return (NSNumber *)[self idForPath:path];
}


//
- (NSObject *)objectValue:(NSString *)path
{
    return [self idForPath:path];
}


//
- (NSInteger)integerValue:(NSString *)path
{
    return [[self idForPath:path] integerValue];
}


#pragma mark - 私有方法

// 解析JSON格式的NSDictionary，将对应值装入对应字段
//
- (void)parserJSONDictionary:(NSDictionary *)dictionary
{
    NSString* message = [dictionary objectForKey:@"message"];
    _message = message;
    
    NSInteger status = [[dictionary objectForKey:@"status"] integerValue];
    _status = status;
    
    NSString* error = [dictionary objectForKey:@"error"];
    _error = error;
    
    NSDictionary* data = [dictionary objectForKey:@"data"];
    _data = data;
}


// 路径字符串分解，并从_data中取出对象返回
//
- (id)idForPath:(NSString *)path
{
    id result;
    
    //非空对象，且对象值长度>0才执行
    if (path && path.length > 0) {
        
        //用.作为切割符，分离路径
        NSArray* params = [path componentsSeparatedByString:@"."];
        
        //初始操作值为_data
        NSDictionary* operator = _data;
        
        //在operator中遍历路径。
        //每次循环operator都会被改变。当循环到末端，不再是NSDictionary类型时，说明没有路径值，将operator设为nil。
        for (NSString* param in params) {
            
            if ([operator isKindOfClass:[NSDictionary class]]) {
                
                operator = [operator objectForKey:param];
            }
            //到达末端，跳出
            if (operator == nil) {

                break;
            }
        }
        
        result = operator;
    }
    
    return result;
}

@end
